package com.youlu.campus.admin.commission.service;

import com.youlu.campus.entity.commission.DistributorGrade;
import com.youlu.campus.entity.commission.dto.DistributorGradeSaveDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : [dengbo]
 * @className : DistributorGradeService
 * @description : [描述说明该类的功能]
 * @createTime : [2023/2/3 13:52]
 */
@Service
public class DistributorGradeAdminService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 虚拟商品保存
     *
     * @param saveDTO
     * @return
     */
    public boolean save(DistributorGradeSaveDTO saveDTO) {
        DistributorGrade grade = mongoTemplate.findOne(Query.query(Criteria.where("id").is(saveDTO.getId())), DistributorGrade.class);
        if (grade == null) {
            grade = new DistributorGrade();
            grade.setCreatedTime(new Date());
            grade.setDeleted(false);
        }
        grade.setName(saveDTO.getName());
        grade.setTotalMoney(saveDTO.getTotalMoney());
        grade.setCommissionRate(saveDTO.getCommissionRate());
        grade.setUpdatedTime(new Date());
        mongoTemplate.save(grade);
        return true;
    }

    public List<DistributorGrade> list() {
        Query query = new Query();
        List<DistributorGrade> list = mongoTemplate.find(query, DistributorGrade.class);
        return list.stream().map(item -> {
            if (item.getCommissionRate() != 0) {
                item.setCommissionRateStr(item.getCommissionRate() + "%");
            }else{
                item.setCommissionRateStr(item.getCommissionRate()+"");
            }
            return item;
        }).sorted(Comparator.comparing(DistributorGrade::getTotalMoney)).collect(Collectors.toList());
    }
}
